﻿using MvvmCross.Core.ViewModels;
using Sidvall.IdentityManager.UI.Messaging;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Sidvall.IdentityManager.UI.ViewModels
{
	public class DashboardViewModel : Sidvall.UI.ViewModels.ViewModelBase
	{
		#region Public Members

		public long? UserCount { get; set; }

		#region EntityCache

		private global::Sidvall.IdentityManager.UI.Entities.Model.EntityCache _EntityCache;
		public global::Sidvall.IdentityManager.UI.Entities.Model.EntityCache EntityCache
		{
			get
			{
				if (_EntityCache == null)
					this.EntityCache = new global::Sidvall.IdentityManager.UI.Entities.Model.EntityCache();
				return _EntityCache;
			}
			set
			{
				_EntityCache = value;
				RaisePropertyChanged("EntityCache");
			}
		}

		#endregion

		// Commands
		#region NewUserCommand

		public ICommand NewUserCommand
		{
			get
			{
				return new MvxCommand(NewUser);
			}
		}

		#endregion
		#region NewUser

		public void NewUser()
		{
			using (var busyManager = new Sidvall.Data.BusyManager(this))
			{
				var parameter = new UserParameter()
				{
					UserId = null,
				};
				ShowViewModel<AspNetUsersViewModel>(parameter);
			}
		}

		#endregion
		#region ShowUsersCommand

		public ICommand ShowUsersCommand
		{
			get
			{
				return new MvxCommand(() => ShowViewModel<AspNetUsersCollectionViewModel>());
			}
		}

		#endregion

		#region StartAsync

		protected async override Task StartAsync()
		{
			var tasks = GetLoadTasks();
			await ViewModelManager.LoadCacheAsync(false, tasks, this.EntityCache);

			RaiseAllPropertiesChanged();
		}

		#endregion

		#endregion
		#region Private Members

		// Tasks
		#region LoadUserCountAsync

		private async Task LoadUserCountAsync()
		{
			this.UserCount = await SystemContext.Current.DataPortal.AspNetUsersManager.GetItemCountAsync();
		}

		#endregion
		#region GetLoadTasks

		private List<Task> GetLoadTasks()
		{
			List<System.Threading.Tasks.Task> tasks;

			tasks = new List<Task>();
			tasks.Add(LoadUserCountAsync());

			return tasks;
		}

		#endregion

		#endregion
	}
}
